﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CompositionPlugin.Service
{
    public class TemporaryFileRepository : ITemporaryFileRepository, IModuleRuntimeServiceGenerator
    {
        public virtual void Initialize() { }

        public string NewTempFile()
        {
            lock (this)
            {
                var filename = Path.GetTempFileName();
                this._fileList.Add(filename);
                return filename;
            }
        }

        public void Clear()
        {
            lock (this)
            {
                foreach (var filename in this._fileList)
                    if (File.Exists(filename))
                        File.Delete(filename);
            }
        }

        public IRuntimeService GetModuleRuntimeService(ModuleDefinition definition, out Type contractType)
        {
            contractType = typeof(IModuleTemporaryFileRepository);
            return new ModuleTemporaryFileRepository();
        }

        public virtual void OnRuntimeDisposing()
        {
            if(SystemRuntime.Current.Configuration.TempFile.AutoClean)
                this.Clear();
        }

        #region private

        private readonly List<string> _fileList = new List<string>();

        #endregion
    }
}
